package com.zkas.munqr;

import java.io.IOException;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.zkas.munqr.camera.CameraConfigurationManager;
import com.zkas.munqr.camera.CameraManager;
import com.zkas.munqr.camera.PreviewCallback;

public class MainActivity extends FragmentActivity implements
		SurfaceHolder.Callback {
	private static final String TAG = MainActivity.class.getSimpleName();

	private MainActivityHandler handler;
	private CameraManager cameraManager;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private TypeSource typeSource;
	private int nIntents=0;
	private SoundPool soundPool;
	private int soundId1;
	private int soundId2;
	private int soundIdExito;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Window window = getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.activity_main);
		hasSurface = false;
		nIntents=0;
		
		this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
		soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
	    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
	        @Override
	        public void onLoadComplete(SoundPool soundPool, int sampleId,
	            int status) {
	          //loaded = true;
	        }
	      });
	    
	    soundId1 = soundPool.load(this, R.raw.sound1, 1);		
	    soundId2 = soundPool.load(this, R.raw.sound2, 1);		
	    soundIdExito = soundPool.load(this, R.raw.soundexito, 1);		
	    
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_settings:
			Intent intent = new Intent(this, SettingActivity.class);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onPause() {
		if (handler != null) {
	      handler.quitSynchronously();
	      handler = null;
	    }
		cameraManager.closeDriver();
		if (!hasSurface) {
			SurfaceView surfaceView = (SurfaceView) findViewById(R.id.camera_preview);
			SurfaceHolder surfaceHolder = surfaceView.getHolder();
			surfaceHolder.removeCallback(this);
		}

		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		cameraManager = new CameraManager(getApplicationContext());
		handler = null;
		typeSource = TypeSource.QR;
		cameraManager.setMode(typeSource);

		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
		viewfinderView.setCameraManager(cameraManager);

		Button qrButton = (Button) findViewById(R.id.QR);
		qrButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				nIntents = 0 ;
				typeSource = TypeSource.QR;
				cameraManager.resetFramingRect();
				cameraManager.setMode(typeSource);
				viewfinderView.invalidate();
			}
		});

		Button cuitButton = (Button) findViewById(R.id.CUIT);
		cuitButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				nIntents = 0 ;
				typeSource = TypeSource.CUIT;
				cameraManager.resetFramingRect();
				cameraManager.setMode(typeSource);
				viewfinderView.invalidate();
			}
		});

		Button manualButton = (Button) findViewById(R.id.Manual);
		manualButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				nIntents = 0 ;
				CuitDialogFragment cuitDialog = new CuitDialogFragment();
				cuitDialog.show(getSupportFragmentManager(), "cuit");
			}
		});

		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.camera_preview);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			// The activity was paused but not stopped, so the surface still
			// exists. Therefore
			// surfaceCreated() won't be called, so init the camera here.
			initCamera(surfaceHolder);
		} else {
			// Install the callback and wait for surfaceCreated() to init the
			// camera.
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		if (surfaceHolder == null) {
			throw new IllegalStateException("No SurfaceHolder provided");
		}
		if (cameraManager.isOpen()) {
			Log.w(TAG,
					"initCamera() while already open -- late SurfaceView callback?");
			return;
		}
		try {
			cameraManager.openDriver(surfaceHolder);
			if (handler == null) {
				handler = new MainActivityHandler(this, cameraManager);
			}
			cameraManager.startPreview();
			viewfinderView.drawViewfinder();

		} catch (IOException ioe) {
			Log.w(TAG, ioe);
		} catch (RuntimeException e) {
			Log.w(TAG, "Unexpected error initializing camera", e);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
		// TODO Auto-generated method stub
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (holder == null) {
			Log.e(TAG,
					"*** WARNING *** surfaceCreated() gave us a null surface!");
		}
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;
		cameraManager.closeDriver();
	}

	public CameraManager getCameraManager() {
		return cameraManager;
	}

	public TypeSource getTypeSource() {
		return typeSource;
	}

	public int getNIntents() {
		return nIntents;
	}

	public void setNIntents(int n) {
		nIntents = n;
	}
	public void drawViewfinder() {
		viewfinderView.drawViewfinder();
	}

	public void handleDecode(String cuit) {
		CuitDialogFragment cuitDialog = new CuitDialogFragment();
		cuitDialog.setCuit(cuit);
		cuitDialog.setActivityHandler(handler);
		cuitDialog.show(getSupportFragmentManager(), "cuit");
	}

	public Handler getHandler() {
		return handler;
	}

	// modeColor es el numero de intento. Para par muestra un color. Impar muestra otro.
	// Modifica color segun par o impar.
	public void setViewStatus(String message, int blinkMSTime, int modeColor){		
		TextView statusView = (TextView) findViewById(R.id.status_view);
		if (blinkMSTime>0)
		{
			Animation anim = new AlphaAnimation(0.0f, 1.0f);
			anim.setDuration(blinkMSTime); //You can manage the time of the blink with this parameter
			anim.setStartOffset(blinkMSTime/2);
			anim.setRepeatMode(Animation.REVERSE);
			anim.setRepeatCount(Animation.INFINITE);
			statusView.startAnimation(anim);			
		}
		else
			statusView.clearAnimation();
			
		if (modeColor % 2 > 0)
			statusView.setTextColor(Color.parseColor("#FAAC58"));
		else
			statusView.setTextColor(Color.parseColor("#FFFF00"));
		
		statusView.setText(message);

		if (message.contains("xito"))
			playSound(soundIdExito);
		else if (message.contains("Procesando")) 
			playSound(soundId2);
		else if (!message.equals("") && !message.contains("leer"))
			playSound(soundId1);
	}
	
	private void playSound(int sId)
	{ 
		AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
	    float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
	    float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
	    float volume = actualVolume / maxVolume;
	      // Is the sound loaded already?  Asumo que si...
	      //if (loaded) {
	    soundPool.play(sId, volume, volume, 1, 0, 1f);
	    Log.e("Test", "Played sound");
	      //}		
	}	
}
